package org.mihalovic.PES.Core.Graph;


import java.util.Collection;
import org.mihalovic.PES.GUI.AppWindow;
import org.mihalovic.PES.data.QueryDomainsHolder;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import edu.uci.ics.jung.graph.DirectedSparseGraph;

import org.mihalovic.PES.data.DataManager;



/**
 * Gets instance of unranked graph.
 */
public class GraphHolder
{
    /**
     * Returns most recent graph according to users domain selection.
     *
     * @return <code>null</code> on fail
     */
    public static DirectedSparseGraph<Node, Edge> GetUnrankedGraph() {
        QueryDomainsHolder holder = AppWindow.getInstance().GetQueryHolder();
        String q = holder.getUserQuery();
        return GetUnrankedGraph(q);
    }


    public static DirectedSparseGraph<Node, Edge> GetUnrankedGraph(String userQuery) {
        DataManager reader = AppWindow.getInstance().GetSourceGraphReader();

        if (reader!=null /*del && reader.isOpen()*/ ) {
            try {
                Set<Node> vertices = reader.GetQueryNodes(userQuery);
                /*List*/Collection<Edge> edges = reader.GetPositiveRatings(userQuery);
                
                DirectedSparseGraph<Node, Edge> graph = new GraphBuilder().Build(vertices, edges);
                Collection<Node> vrts = graph.getVertices();
                for(Node n : vrts)
                    n.setHasInEdges(graph.getInEdges(n).size() > 0);

                return graph;
//del            } catch (SourceGraphReaderException sgre) {
//                Logger.getLogger(GraphHolder.class.getName()).log(Level.SEVERE, null, sgre);
            } catch (GraphException ge){
                Logger.getLogger(GraphHolder.class.getName()).log(Level.SEVERE, null, ge);
            }
        }
        //TODO: else message

        return new DirectedSparseGraph<Node, Edge>() /*null*/;
    }
}
